package com.tarena.lbs.service.impl;

import com.tarena.lbs.dto.FileUploadResult;
import com.tarena.lbs.entity.AttachFile;
import com.tarena.lbs.repository.AttachFileRepository;
import com.tarena.lbs.service.FileStorageService;
import com.tarena.lbs.util.FileUtils;
import com.tarena.lbs.util.UUIDGenerator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Date;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Service
public class FileStorageServiceImpl implements FileStorageService {

    @Value("${file.upload.dir}")
    private String uploadDir;

    @Value("${file.access.url.prefix}")
    private String accessUrlPrefix;

    private final AttachFileRepository attachFileRepository;

    // 推荐使用构造器注入
    public FileStorageServiceImpl(AttachFileRepository attachFileRepository) {
        this.attachFileRepository = attachFileRepository;
    }

    @Override
    public FileUploadResult uploadFile(MultipartFile file, Long userId, String userName) {
        FileUploadResult result = new FileUploadResult();

        try {
            String fileUuid = UUIDGenerator.generate();
            String fileExtension = FileUtils.getFileExtension(file.getOriginalFilename());
            String savedFileName = fileUuid + (fileExtension.isEmpty() ? "" : "." + fileExtension);
            String filePath = uploadDir + "/" + savedFileName;

            // 明确的IO操作
            Path path = Paths.get(filePath);
            Files.createDirectories(path.getParent());
            file.transferTo(path);

            String fileUrl = accessUrlPrefix + savedFileName;

            AttachFile attachFile = new AttachFile();
            attachFile.setFileUuid(fileUuid);
            attachFile.setClientFileName(file.getOriginalFilename());
            attachFile.setContentLength(file.getSize());
            attachFile.setContentType(file.getContentType());
            attachFile.setCreateUserId(userId);
            attachFile.setCreateUserName(userName);

            attachFileRepository.insert(attachFile);

            result.setFileId(fileUuid);
            result.setFileName(file.getOriginalFilename());
            result.setFileUrl(fileUrl);
            result.setFileSize(file.getSize());
            result.setFileType(attachFile.getContentType());
            result.setSuccess(true);
            result.setMessage("File uploaded successfully");

        } catch (IOException e) {
            result.setSuccess(false);
            result.setMessage("File upload failed: " + e.getMessage());
        }

        return result;
    }

    @Override
    public boolean deleteFile(String fileUuid) {
        AttachFile attachFile = attachFileRepository.findByUuid(fileUuid);
        if (attachFile == null) return false;

        String fileExtension = FileUtils.getFileExtension(attachFile.getClientFileName());
        String filePath = uploadDir + "/" + fileUuid + (fileExtension.isEmpty() ? "" : "." + fileExtension);

        boolean deleted = FileUtils.deleteFile(filePath);
        if (deleted) {
            attachFileRepository.delete(attachFile.getId());
            return true;
        }
        return false;
    }
}